package com.example.chapter3.controller;

import com.example.chapter3.entity.User;
import com.example.chapter3.service.UserService;
//import com.example.chapter3.service.iml.LoginService;
import com.example.chapter3.service.iml.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Controller
public class UserContorller {
    @Autowired
    private LoginService loginService;
    @RequestMapping(value = {"/index","/main"})
    public String index(){
        log.info("打开主页");
        return "index";         //forward:index.html:用于访问静态html，在static中的
    }
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public ModelAndView showlogin(ModelAndView mv){
        log.info("打开登录界面");
        mv.setViewName("login");
        return mv;
    }
    @RequestMapping(value = "/login",name = "登录验证",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView userlogin(ModelAndView mv,User user){
        if (loginService.login(user.getUsername(), user.getPassword())){
            log.info("跳转到主页");
            mv.setViewName("index");
            mv.addObject("user",user);
        }
         else {
             mv.setViewName("login");
             mv.addObject("error","登录失败");

        }
         return mv;
    }
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public ModelAndView showregister(ModelAndView modelAndView){
        User user = new User();
        //添加实体类对象
        modelAndView.addObject("user",user);
        //指定跳转的页面
        modelAndView.setViewName("register");
        return modelAndView;
    }
    @Autowired
    private UserService userService;
    //接受注册请求
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public ModelAndView handleregister(ModelAndView modelAndView,User user){
        //验证用户名是否存在
        try {
            userService.register(user);
            modelAndView.addObject("success","注册成功");
        } catch (Exception e) {
            modelAndView.addObject("error","注册失败");
        }
        return modelAndView;
    }

}
